package com.atstudying.mall.ware.service.impl;

import com.atstudying.common.exception.NoStockException;
import com.atstudying.common.utils.PageUtils;
import com.atstudying.common.utils.Query;
import com.atstudying.mall.ware.dao.WareSkuDao;
import com.atstudying.mall.ware.entity.WareSkuEntity;
import com.atstudying.mall.ware.service.WareSkuService;
import com.atstudying.mall.ware.vo.OrderItemVo;
import com.atstudying.mall.ware.vo.SkuHasStockVo;
import com.atstudying.mall.ware.vo.WareSkuLockVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    WareSkuDao wareSkuDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                new QueryWrapper<WareSkuEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * {
     page: 1,//当前页码
     limit: 10,//每页记录数
     sidx: 'id',//排序字段
     order: 'asc/desc',//排序方式
     wareId: 123,//仓库id
     skuId: 123//商品id
     }
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {


        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();

        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)){
            wrapper.eq("ware_Id",wareId);

        }

        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId)){
            wrapper.eq("sku_Id",skuId);

        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);

    }

    @Override
    public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) {

        List<SkuHasStockVo> collect = skuIds.stream().map(skuId -> {
            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();

            //查询当前sku的总库存量
            Long count= baseMapper.getSkuStock(skuId);
            skuHasStockVo.setSkuId(skuId);
            skuHasStockVo.setHasStock(count==null?false:count>0);
            return skuHasStockVo;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 为某一个订单锁定库存
     * @param vo
     * @return
     */
    //默认是锁库存异常都会回滚
    @Transactional(rollbackFor = NoStockException.class)
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {

        //1：按照下单的收货地址，找到一个就近的仓库，锁定库存：太麻烦不这么做
        //1：找到每个商品在那个仓库都有库存
        List<OrderItemVo> locks = vo.getLocks();

        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock skuWareHasStock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            skuWareHasStock.setSkuId(skuId);
            //查询这个商品在哪里有库存
            List<Long> wareIds= wareSkuDao.listWareIdHasSkuStock(skuId);

            skuWareHasStock.setNum(item.getCount());
            skuWareHasStock.setWareId(wareIds);
            return skuWareHasStock;
        }).collect(Collectors.toList());

        Boolean allLock=false;
        //2：锁定库存
        for (SkuWareHasStock hasStock:collect
             ) {
            Boolean skuStocked=false;
            Long skuId = hasStock.getSkuId();
            List<Long> wareIds = hasStock.getWareId();
            if (wareIds==null||wareIds.size()==0){
                //没有任何仓库有这个商品的库存

                throw  new NoStockException(skuId);
            }
            for (Long wareId:wareIds){

                //成功就返回1，否则返回0
               Long count= wareSkuDao.lockSkuStock(skuId,wareId,hasStock.getNum());
               if (count==1){
                   //当前仓库锁成功
                   skuStocked=true;
                   break;
               }else {
                   //当前仓库锁失败，重试下一个仓库
               }
            }
            if (skuStocked==false){
                //当前商品所有库存都没有锁住
                throw  new NoStockException(skuId);
            }
        }

        //3：肯定都是全部锁定成功的

        return true;
    }

    @Data
    class SkuWareHasStock{
        private Long skuId;
        private Integer num;
        private List<Long> wareId;
    }

}